package fex

import (
	"bytes"
	"gitee.com/yysf_xin/dplog/pkg/extracter"
	"gitee.com/yysf_xin/dplog/pkg/extracter/java"
	"gitee.com/yysf_xin/dplog/pkg/slog"
	"gitee.com/yysf_xin/go-common/tools"
	"strings"
	"time"
)

var (
	LEVEL = []byte{'D', 'I', 'W', 'E'}
)

type MakeLog struct {
	Name string
	LogParser
	extracter.SubLine
	javaOpt *java.Opt
}

func (l *MakeLog) Custom(c *slog.Collect) {
	c.Opt.MultiLine = true
}

//func (l *MakeLog) MakeSubMsg(ref *slog.MessageRef, sub []byte) {
//	m := ref.GetRef().(*Message)
//	m.SubMessage = tools.BytesToString(sub)
//}

func NewMakeLog(opt *java.Opt, name string) *MakeLog {
	return &MakeLog{Name: name, SubLine: java.NewExtract(opt), javaOpt: opt}
}

func (l *MakeLog) Rest() {
	l.SubLine.Rest()
}

func (l *MakeLog) New() slog.Message {
	return new(slog.MessageImpl)
}

func (l *MakeLog) Filter(ref *slog.MessageRef) bool {
	msg := ref.GetRef().(*slog.MessageImpl)
	msg.Level = tools.BytesToString(l.Level)
	msg.Logger = tools.BytesToString(l.Logger)

	if len(msg.Level) > 0 && bytes.IndexByte(LEVEL, msg.Level[0]) == 0 {
		if !strings.HasPrefix(msg.Logger, l.javaOpt.Package) {
			filter := true
			for _, v := range l.javaOpt.Mybatis {
				if strings.HasPrefix(msg.Logger, v) {
					filter = false
					break
				}
			}
			if filter {
				return filter
			}
		}
	}
	msg.Thread = tools.BytesToString(l.Thread)
	msg.AppName = tools.BytesToString(l.Trace.AppName)
	msg.TraceID = tools.BytesToString(l.Trace.Trace)

	msg.Time = time.Date(l.Year, time.Month(l.Month), l.Day, l.Hour, l.Minute, l.Second, l.Micro*1e6, time.Local)
	msg.Level = tools.BytesToString(l.Level)
	//msg.P = tools.BytesToString(l.P)
	msg.Thread = tools.BytesToString(l.Thread)
	msg.AppName = tools.BytesToString(l.Trace.AppName)
	msg.TraceID = tools.BytesToString(l.Trace.Trace)
	msg.Logger = tools.BytesToString(l.Logger)
	msg.Method = tools.BytesToString(l.Method)
	msg.Message = tools.BytesToString(l.Message)

	le := len(msg.Message) - 1
	if le > 0 && msg.Message[le] == ']' {
		msg.Message = msg.Message[:le]
	}
	if msg.AppName == "" {
		msg.AppName = l.Name
	}

	// 没有traceId
	if len(msg.TraceID) < 10 {
		msg.TraceID = ""
	}

	return false
}
